package com.ruoyi.dl.controller;

import com.ruoyi.dl.domain.DlUser;
import com.ruoyi.dl.domain.DlWithdraw;
import com.ruoyi.dl.service.IDlOrdersService;
import com.ruoyi.dl.service.IDlUserService;
import com.ruoyi.dl.service.IDlWithdrawService;
import com.ruoyi.dl.service.impl.RedisUtil;
import com.ruoyi.dl.wxPay.Tool;
import com.ruoyi.dl.wxPay.WXJSPay;
import com.ruoyi.dl.wxPay.util.XMLUtil;
import org.apache.commons.lang3.StringUtils;
import org.jdom2.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping("wechat/wxPay")
public class WxPayController {

	@SuppressWarnings("unused")
	private String errorMessage;
	@Autowired
	IDlOrdersService ordersService;

	@Autowired
	IDlUserService dlUserService;
	@Autowired
	IDlWithdrawService dlWithdrawService;
	/**
	 *
	 */
	@Autowired
	RedisUtil redisUtil;

	/**
	 * 微信支付
	 * @Description 
	 * @return
	 * Create at: 2020-05-21 14:19:10
	 * @author: ccm
	 * Revision:
	 *    2020-05-21 14:19:10 - first revision by ccm
	 *
	 */
	@CrossOrigin
	@SuppressWarnings("unchecked")
	@PostMapping("wxPrePay")
	@ResponseBody                                          //金额           //编号
	public Map<String, String> wxPay(String openId,String user_fee, String total_fee,String out_trade_num){
		Map<String, String> wxPayParamMap = new HashMap<>();
		try {
				if(StringUtils.isNotBlank(openId)&&StringUtils.isNotBlank(total_fee)&&StringUtils.isNotBlank(out_trade_num)&&StringUtils.isNotBlank(user_fee)) {
					total_fee=Tool.getMoney(total_fee);
					//redisUtil.set("openId", openId);
					DlUser dlUser=dlUserService.selectDlUserByOpenId(openId);
					DlWithdraw dlWithdraw=new DlWithdraw();
					dlWithdraw.setMoneyVal(new BigDecimal(user_fee));
					dlWithdraw.setUserId(dlUser.getId());
					dlWithdraw.setOperate(0);
					dlWithdraw.setCreateTime(new Date());
					dlWithdraw.setRemark("充值");
					dlWithdrawService.insertDlWithdraw(dlWithdraw);

					wxPayParamMap = WXJSPay.jsApiPay(openId, total_fee, String.valueOf(dlWithdraw.getId()));

				}else {
					wxPayParamMap.put("status","500");
					wxPayParamMap.put("msg","支付失败");
				}
		} catch (JDOMException | IOException e) {
			e.printStackTrace();
			//wxPayParamMap.put("status", "0");//网络已断开
		}
		/*Map<String,String> map = new HashMap<String, String>();
		map.put("appId", wxPayParamMap.get("appId"));
		map.put("timeStamp", wxPayParamMap.get("timeStamp"));
		map.put("nonceStr", wxPayParamMap.get("nonceStr"));
		map.put("wxPackage", wxPayParamMap.get("package"));
		map.put("signType", wxPayParamMap.get("signType"));
		map.put("paySign", wxPayParamMap.get("paySign"));*/
		return wxPayParamMap;
		//return wxPayParamMap;
	}
	
	/**
	 * 微信Native支付
	 * @Description 
	 * @param token
	 * @param orderSn
	 * @return
	 * Create at: 2020-06-29 15:32:29
	 * @author: zrl
	 * Revision:
	 *    2020-06-29 15:32:29 - first revision by zrl
	 *
	 */
//	@CrossOrigin
//	@RequestMapping("wxNativePay")
//	@ResponseBody
//	public Map<String, Object> wxNativePay(String token, String orderSn){
//		Map<String, Object> map = new HashMap<>();
//		try {
//			DlOrders order =new DlOrders();
//			order.setOrdersNumber(orderSn);
//			order = ordersService.selectDlOrdersByOrdersNumber(order);
//			if(order!=null) {
//				//对金额进行转换形式
//				BigDecimal totalMoney = order.getDlOrdersGoods().getOrderPrice();
//				//实际金额
//				//String total_fee = Tool.getMoney(String.valueOf(totalMoney));
//				//测试一分钱
//				String total_fee = "1";
//				String out_trade_num = orderSn;//订单编号
//				String QRCodeUrl = WXJSPay.nativePay(out_trade_num, out_trade_num, total_fee);
//				map.put("status", 1);
//				map.put("data",QRCodeUrl);
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//			map.put("status", 0);
//			map.put("msg", "网络错误");
//		}
//		return map;
//	}
//

	/**
	 *
	 */
	@PostMapping("withdraw")
	@ResponseBody
	public Map<String, String> withdraw( String openId, String transferMoney){
		Map<String, String> wxPayParamMap = null;
		try {
			wxPayParamMap = new HashMap<>();
			DlUser dlUser=dlUserService.selectDlUserByOpenId(openId);
			if(dlUser.getBalance().compareTo(new BigDecimal(10))>-1&&dlUser.getBalance().compareTo(new BigDecimal(transferMoney))>-1) {
				BigDecimal fee = new BigDecimal(transferMoney);
				if (fee.compareTo(new BigDecimal(10)) == 1 && fee.compareTo(new BigDecimal(200)) == -1) {
					fee = fee.subtract(new BigDecimal(2));
				} else if (fee.compareTo(new BigDecimal(200)) > -1 && fee.compareTo(new BigDecimal(2500)) == -1) {
					fee = fee.subtract(fee.multiply(new BigDecimal(0.1)));
				} else if (fee.compareTo(new BigDecimal(2500)) > -1){
					fee = fee.subtract(new BigDecimal(25));
				}
				DlWithdraw dlWithdraw = new DlWithdraw();
				dlWithdraw.setMoneyVal(fee);
				dlWithdraw.setUserId(dlUser.getId());
				dlWithdraw.setOperate(0);
				dlWithdraw.setCreateTime(new Date());
				dlWithdraw.setRemark("提现");
				dlWithdrawService.insertDlWithdraw(dlWithdraw);
				wxPayParamMap = WXJSPay.transferPay(String.valueOf(dlWithdraw.getId()), openId, new BigDecimal(transferMoney));
				if("SUCCESS".equals((String)wxPayParamMap.get("result_code"))){
					dlUser.setBalance(dlUser.getBalance().subtract(fee));
					dlUserService.updateDlUser(dlUser);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			wxPayParamMap = new HashMap<>();
			wxPayParamMap.put("status","500");
			wxPayParamMap.put("msg","提现失败");
		}
		return wxPayParamMap;
	}
	
	/**
	 * 微信异步回调
	 * @Description 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws JDOMException
	 * Create at: 2020-05-21 14:18:14
	 * @author: zxh
	 * Revision:
	 *    2020-05-21 14:18:14 - first revision by zxh
	 *
	 */
	@SuppressWarnings({"unlikely-arg-type", "unused", "rawtypes" })
	@RequestMapping("/wxNotify")
	@ResponseBody
	@CrossOrigin
	public void wxNotify(HttpServletRequest request,HttpServletResponse response) throws IOException, JDOMException{
		//读取参数  
		InputStream inputStream ;  
		StringBuffer sb = new StringBuffer();  
		inputStream = request.getInputStream();  
		String s ;  
		BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));  
		while ((s = in.readLine()) != null){  
			sb.append(s);  
		}  
		in.close();  
		inputStream.close();  
		//解析xml成map  
		Map<String, String> m = new HashMap<String, String>();  
		m = XMLUtil.doXMLParse(sb.toString());
		for(Object keyValue : m.keySet()){
			System.out.println(keyValue+"="+m.get(keyValue));
		}
		//过滤空 设置 TreeMap  
		TreeMap<String,String> packageParams = new TreeMap<String,String>();     
		Iterator it = m.keySet().iterator();  
		while (it.hasNext()) {  
			String parameter = (String) it.next();  
			String parameterValue = m.get(parameter);  
			
			String v = "";  
			if(null != parameterValue) {  
				v = parameterValue.trim();  
			}  
			packageParams.put(parameter, v);  
		}  
		//判断签名是否正确  
		String resXml = "";  
//		if(WeiXinSignAndPackage.isWXSign(packageParams)) {
			if("SUCCESS".equals((String)packageParams.get("result_code"))) {
				// 这里是支付成功  
				//////////执行自己的业务逻辑////////////////  
				String mch_id = (String) packageParams.get("mch_id"); //商户
				String openId = (String) packageParams.get("openid");  //用户标识
				String out_trade_no = (String) packageParams.get("out_trade_no"); //商户订单号
				String total_fee =String.valueOf( new BigDecimal((String) packageParams.get("total_fee")).divide(new BigDecimal(100)));//订单金额
				String transaction_id = (String) packageParams.get("transaction_id"); //微信支付订单号
				//根据订单id获取订单  判断订单状态 一次回调
				DlWithdraw dlWithdraw= dlWithdrawService.selectDlWithdrawById(Integer.valueOf(out_trade_no));
				DlUser dlUser = dlUserService.selectDlUserByOpenId(openId);
				if (dlWithdraw!=null&&dlWithdraw.getType().equals(0)){
					BigDecimal fee = new BigDecimal(total_fee);
					if (fee.compareTo(new BigDecimal(12)) == 1 && fee.compareTo(new BigDecimal(202)) == -1) {
						fee = fee.subtract(new BigDecimal(2));
					} else if (fee.compareTo(new BigDecimal(202)) > -1 && fee.compareTo(new BigDecimal(2525)) == -1) {
						fee = fee.subtract(fee.multiply(new BigDecimal(0.1)));
				} else if (fee.compareTo(new BigDecimal(2525)) > -1){
						fee = fee.subtract(new BigDecimal(25));
					}
					if (dlUser != null) {
						dlUser.setBalance(dlUser.getBalance().add(fee));
					}
					dlWithdraw.setType(2);
					dlWithdrawService.updateDlWithdraw(dlWithdraw);
					dlUserService.updateDlUser(dlUser);
				}
				this.errorMessage = "支付成功";
				resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
						+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";

			}else {  
//				logger.info("支付失败,错误信息：" + packageParams.get("err_code"));  
				this.errorMessage = "支付失败,错误信息：" + packageParams.get("err_code");
				resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"  
				+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";  
			}    
		System.out.println(resXml);
		//------------------------------  
		//处理业务完毕  
		//------------------------------  
		BufferedOutputStream out = new BufferedOutputStream(  
		response.getOutputStream());  
		out.write(resXml.getBytes());  
		out.flush();  
		out.close();  
	
	}
	




}
